// let utils = require('../../../../utils/util');
const { http } = require('../../../../utils/apiutils.js');
import {
  formatTime
} from '../../../../utils/util.js'
let miny=[];
let maxy=[];
for(let i=16;i<65; i++){
  miny.push(i)
  maxy.push(i)
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img: [],
    type: '1',
    video: [],
    filter(type, options) {
      if (type === 'minute') {
        return options.filter(option => option == "00");
      }
      return options;
    },
    fileListImg: [],
    gw: '',
    currentDate: new Date().getTime(),
    currentTime: new Date().getHours() + ':00',
    clickPickerKey: '',
    pickershow: false,
    payType: ['小时', '天'],
    sex: ['男', '女', '不限'],
    ageArr: ['15-25', '25-35', '35-45', '45-55', '55-65'],
    weekArr: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    allWork: [],
    peopleArr: [],
    peopleNum: 0,
    fileListImg: [],
    fileListVideo: [],
    checkb: false,
    loading: false,
    addrList: [],
    factoryJob: {
      images: [],
      type: '1',  // 1 短期  2长期
      postType: '1',   // 1兼职  2全职
      name: "",
      description: "",
      basicSalary: "",
      payType: "小时",
      isPlay: 2,   //  1平台结算  2非平台结算
      registerTime: "",
      asOfTime: "",
      startTime: "",
      startDate: '',
      leaveDate: '',
      leaveTime: "",
      sex: "不限",
      education: "不限",
      age: '',
      dayofweek: [],
      floatSalary: 10
    },
    copefactoryJob: {},
    checked: 1,
    isPay: false,  // 是否已经支付过了
    wxPayInfo: {},
    inputFocus:'none',
    gwinput:'',
    toast:false,
    workTime:'',  // 工作时间
    fy:'',  // 费用合计 
    detePopup:false,
    ageDate:[14,19],
    miny,
    maxy,
    addJobBackId:'',// 添加岗位后返回的岗位id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 进入先获取地址列表以供选择
    this.getDataList();
    // 正式需放开
    this.getgw();
    let copy = JSON.parse(JSON.stringify(this.data.factoryJob));
    this.setData({
      copefactoryJob: copy,
    })
    this.setData({
      ["factoryJob.contactPerson"]:getApp().globalData.factoryInfo.contactName,
      ["factoryJob.contactPhone"]:getApp().globalData.factoryInfo.factoryPhone
    })
  },

  onChange(event) {
    this.setData({
      ['factoryJob.postType']: event.detail,
    });
  },
  afterRead1(event) {
    const {
      file
    } = event.detail;
    if (file.type == "video") {
      this.setData({
        afterRead(event) {
          const {
            file
          } = verifyevent.detail;
          if (file.type == "image") {
            this.setData({
              fileListVideo: [...this.data.fileListVideo, file],
            })
          } else {
            wx.showToast({
              title: '请上传图片文件',
            })
          }
          console.log("0000000", file);
        },
      })
    } else {
      wx.showToast({
        title: '请上传视频文件',
      })
    }
    // console.log("0000000", file);

  },
  deletaImg: function (e) {
    //  console.log("-----",e);
    let index = e.detail.index;
    this.data.fileListImg.splice(index, 1);
    this.setData({
      fileListImg: this.data.fileListImg,
    })
  },
  tabClick(event) {
    let key = event.currentTarget.dataset.key;
    let val = event.currentTarget.dataset.val;
    this.setData({
      ['factoryJob.' + [key]]: val,
      inputFocus:'none',
      gwinput:''
    })
  },
  tabClick1(event) {
    let key = event.currentTarget.dataset.key;
    let val = event.currentTarget.dataset.val;
    let arr = JSON.parse(JSON.stringify(this.data.factoryJob.dayofweek));
    if (arr.includes(val)) {
      arr.splice(arr.indexOf(val), 1);
    } else {
      arr.push(val)
    }
    this.setData({
      ['factoryJob.dayofweek']: arr
    })
  },
  input(event) {
    let key = event.currentTarget.dataset.key;
    let val = event.detail.value;
    let inputFocus = this.data.inputFocus
    if(key=='name'){
      inputFocus="1rpx solid #347DFB"
    }
    this.setData({
      ['factoryJob.' + [key]]: val,
      inputFocus
    })
  },
  datePickerClick(event) {
    let key = event.currentTarget.dataset.key;
    this.setData({
      clickPickerKey: key,
      pickershow: true
    })
  },
  confirm(event) {
    let val = event.detail;
    let key = this.data.clickPickerKey;
    console.log(new Date(val))
    let data = new Date(val)
    console.log(formatTime(data))
    this.setData({
      ['factoryJob.' + [key]]: formatTime(val),
      pickershow: false
    })
  },
  confirm1(event) {
    let val = event.detail;
    let key = this.data.clickPickerKey;
    console.log(event)
    this.setData({
      ['factoryJob.' + [key]]: val,
      pickershow: false
    })
  },
  onClose() {
    this.setData({
      pickershow: false
    })
  },
  pickerClick(event) {
    let item = event.currentTarget.dataset.key;
    let index = event.detail.value;
    let key = null;
    let val = null;
    switch (item) {
      case 'payType':
        val = this.data[item][index];
        key = item;
        break;
      case 'sex':
        val = this.data[item][index];
        key = item;
        break;
      case 'age':
        val = this.data.ageArr[index];
        key = item;
        break;
    }
    this.setData({
      ['factoryJob.' + [key]]: val
    })
  },
  onclcickShowAddress(event) {
    let key = event.currentTarget.dataset.key;
    if (key == 'add') {
      wx.navigateTo({
        url: '/pages/me/pages/address/address?type=add',
        success: (result) => { },
        fail: (res) => { },
        complete: (res) => { },
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/me/pages/address/address?type=1',
      success: (result) => { },
      fail: (res) => { },
      complete: (res) => { },
    })
  },
  getgw() {
    wx.showLoading({
      mask: true
    })
    // 获取可选岗位
    console.log(http)
    http.getAllJob({}, (res) => {
      wx.hideLoading()
      if (res.code == 0) {
        this.setData({
          allWork: res.data
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: "none",
        })
      }
    }, (err) => {
      wx.hideLoading()
    })
  },
  verify() {
    let params = JSON.parse(JSON.stringify(this.data.factoryJob));
    if (this.loading) return;
    this.data.loading = true;
    if (params.type == 1) {
      if (!params.startDate || !params.leaveDate) {
        wx.showToast({
          title: '日期不能为空',
          icon: "none"
        })
        this.data.loading = false;
        return false;
      }
    } else {
      if (!(params.dayofweek.length > 0)) {
        wx.showToast({
          title: '工作日不能为空',
          icon: "none"
        })
        this.data.loading = false;
        return false;
      }
    }
    if (!params.startTime || !params.leaveTime) {
      wx.showToast({
        title: '时间不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
    }
    if (!params.basicSalary) {
      wx.showToast({
        title: '薪酬金额不正确',
        icon: "none"
      })
      this.data.loading = false;
      return false;
    }
    if (params.payType=='天'&&params.basicSalary<31) {
      wx.showToast({
        title: '全职薪酬不能低于30',
        icon: "none"
      })
      this.data.loading = false;
      return false;
    }
    if (params.payType=='小时'&&params.basicSalary<4) {
      wx.showToast({
        title: '兼职薪酬不能低于3',
        icon: "none"
      })
      this.data.loading = false;
      return false;
    }
    if (!params.number) {
      wx.showToast({
        title: '人数不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
    }
    if (!params.age) {
      wx.showToast({
        title: '年龄不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
    }
    if (!params.workerPlace) {
      wx.showToast({
        title: '工作地址不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
    }
    if (!params.contactPerson || !params.contactPhone) {
      wx.showToast({
        title: '联系人不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
    }

    if (params.shor == 1) {
      params.startTime = params.startDate + ' ' + params.startTime + ":00";
      params.leaveTime = params.leaveDate + ' ' + params.leaveTime + ":00";
      if (new Date(params.startTime).getTime() >= new Date(params.leaveTime).getTime()) {
        wx.showToast({
          title: '开始日期时间需小于结束日期时间',
          icon: "none"
        })
        this.data.loading = false;
        return false;
      }
    }
    if (!(this.data.fileListImg.length > 0)) {
      wx.showToast({
        title: '请上传一张封面图',
        icon: "none"
      })
      this.data.loading = false;
      return false;
    }
    // if(!isPay){
    //   http.createOrder(100,res=>{
    //     if(res.code==0){
    //       this.pay(res,()=>{
    //         if (this.data.fileListImg.length > 0) {
    //           this.upDataFile(this.data.fileListImg, 0, 1);
    //           return false;
    //         }
    //       });
    //     }else{
    //       wx.showToast({
    //         title: res.message,
    //         icon:"none"
    //       })
    //     }
    //   },err=>{
    //     wx.showToast({
    //       title: err,
    //       icon:'none'
    //     })
    //   })

    //   return ;
    // }

debugger
    let workTime =(this.data.factoryJob.payType=='天'?
    ((new Date(this.data.factoryJob.leaveDate).getTime()-new Date(this.data.factoryJob.startDate).getTime())/3600000/24+1):(this.data.factoryJob.leaveTime[0]+this.data.factoryJob.leaveTime[1]) - (this.data.factoryJob.startTime[0]+this.data.factoryJob.startTime[1]));
    let fy=0;
    fy = workTime*this.data.factoryJob.basicSalary*this.data.factoryJob.number
    if(this.data.factoryJob.postType==2){
        fy+=(this.data.factoryJob.floatSalary)*this.data.factoryJob.number;
        if(this.data.factoryJob.isPlay==2){
          fy = this.data.factoryJob.floatSalary*this.data.factoryJob.number;
        }
    }
    console.log(params)
    this.setData({
      toast:true,
      workTime:workTime+this.data.factoryJob.payType,
      fy:fy
    })
    
  },
  pay(res, fn) {
    wx.requestPayment({
      nonceStr: res.nonceStr,
      package: res.package,
      paySign: res.paySign,
      signType: res.signType,
      timeStamp: res.timeStamp,
      success(res) {
        fn()
      },
      fail(err) {
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        })
      }
    })
  },
  dingyue() {
    // getApp().globalData.dingyue(this.verify);
  
    this.verify();
    
  },
  submit() {
    wx.showLoading({
      mask: true
    })
    let params = JSON.parse(JSON.stringify(this.data.factoryJob));
    if (params.type == 1) {
      params.startTime = params.startDate + ' ' + params.startTime + ":00";
      params.leaveTime = params.leaveDate + ' ' + params.leaveTime + ":00";
    } else if (params.type == 2) {
      params.startTime = formatTime(new Date()) + ' ' + params.startTime + ":00";
      params.leaveTime = formatTime(new Date()) + ' ' + params.leaveTime + ":00";
    }
    params.minAge = params.age.split('-')[0];
    params.maxAge = params.age.split('-')[1];
    params.basicSalary = params.basicSalary * 100;
    if (params.postType == 2) {
      params.floatSalary = params.floatSalary * 100;
    }
    let _this = this;
    if(params.postType==1){
      params.isPlay=1
    }
    console.log(params)
    debugger
    if (this.data.factoryJob.id) {
      http.updatePost(this.data.factoryJob,
        function (res) {
          wx.hideLoading()
          if (res.success) {
            wx.showModal({
              title: "提示",
              content: "修改岗位信息成功",
              showCancel: false,
              success: function () {
                wx.navigateBack({
                  delta: 1,
                });

              },
            })
          } else {
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
        },
        function (err) {
          wx.hideLoading()
        })
    } else {
      console.log("--保存信息--")
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      debugger
      http.addfactoryJob(params,
        function (res) {
          wx.hideLoading()
          if (res.success) {
            wx.showModal({
              title: "提示",
              content: "创建岗位成功,请耐心等待合作公司发布",
              showCancel: false,
              success: function () {
                wx.reLaunch({
                  url: '/pages/tabBar/home/index',
                })
              },
            })
            // _this.createWxPay(res.data.data.id,res.data.data.total);
            this.setData({
              addJobBackId:res.data.data.id
            })
            
            // factoryId
          } else {
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
        },
        function (err) {
          wx.hideLoading()
        })

    }
    wx.hideLoading({})
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    if (file.type == "image") {
    this.setData({
      fileListImg: [...this.data.fileListImg, file],
    })
    } else {
      wx.showToast({
        title: '请上传图片文件',
      })
    }
  },
  check(event) {
    let key = event.currentTarget.dataset.key;
    switch (key) {
      case 'isPlay':
        this.setData({
          ['factoryJob.isPlay']: event.detail ? 2 : 1
        })
        break;
      case 'checkb':
        this.setData({
          checkb: !this.data.checkb
        })
        wx.nextTick(() => {
          this.setData({
            ['factoryJob.type']: event.detail ? 2 : 1
          })
        })
        break;
    }
  },
  upDataFile(data, index, type) {
    let item = data[index];
    console.log("-----", item);
    var that = this;
    var p = {
      url: item.url,
      name: "file",
      formData: {},
    }
    wx.showLoading({mask:true})
    http.upDataFile(p,
      function (res) {
        console.log("---上传图片-", res);
        wx.hideLoading({
          success: (res) => {},
        })
        if (res.code == 0) {
          if (type == 1) {
            that.data.img.push(res.data);
            if (index == data.length - 1) {
              that.data.factoryJob.images = that.data.img;
              if (that.data.fileListVideo.length > 0) {
                that.upDataFile(that.data.fileListVideo, 0, 2);
                that.data.loading = false;
              } else {
                that.submit()
                that.data.loading = false;
              }
            } else {
              console.log("--继续执行--", index, data.length - 1);
              that.upDataFile(data, index + 1, type)
            }
          } else if (type == 2) {
            that.data.video.push(res.data);
            if (index == data.length - 1) {
              that.data.factoryJob.video = that.data.video;
              that.submit()
              that.data.loading = false;
            } else {
              that.upDataFile(data, index + 1, type)
              that.data.loading = false;
            }
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: "nene",
          })
          that.data.loading = false;
        }


      },
      function (err) {
        wx.hideLoading()
        that.data.loading = false;
      })
  },
  reset() {
    this.setData({
      factoryJob: Object.assign({}, this.data.copefactoryJob),
      images: [],

      fileListImg: [],
      fileListVideo: []
    })
  },
  btnclick(event) {
    // 招聘费用 加减按钮 事件
    let key = event.currentTarget.dataset.key;
    let val = this.data.factoryJob.floatSalary;
    if (key == 1) {
      val = val + 1
    } else {
      val = val > 10 ? (val - 1) : val
    }
    this.setData({
      ['factoryJob.floatSalary']: val
    })
  },
  getDataList: function () {
    // 获取地址列表
    var that = this;
    http.getAddressList({},
      function (res) {
        wx.hideLoading()
        console.log("-----已完成任务列表---", res);
        if (res.success) {
          that.setData({
            addrList: res.data.records
          })
          console.log(that.data.addrList)
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })
  },
  addrpicker(event) {
    // 地址选择 赋值
    let index = event.detail.value;
    let indexDate = this.data.addrList[index];
    this.setData({
      "factoryJob.workerPlace": indexDate.address + (indexDate.remark!=null?indexDate.remark:''),
      "factoryJob.lat": indexDate.lat,
      "factoryJob.lng": indexDate.lng,
    })
  },
  createWxPay(id,money) {
    http.createOrder(`${id}/${money}`, res => {
      wx.requestPayment({
        nonceStr: res.nonceStr,
        package: res.package,
        paySign: res.paySign,
        signType: res.signType,
        timeStamp: res.timeStamp,
        success(res) {
          // 支付成功才发送消息通知
          
          wx.showModal({
            title: "提示",
            content: "创建岗位成功,请耐心等待合作公司发布",
            showCancel: false,
            success: function () {
              wx.reLaunch({
                url: '../../../index/index',
              })
              // wx.navigateBack({
              //   delta: 1,
              // })
            },
            
          })
          try {
            http.subMsgforCreatePost(this.data.addJobBackId, function (res1) {
            }, function (res1) {
              console.log(res1)
            });
          } catch (error) {
            console.log(error)
          }
        },
        fail(err) {
          wx.showToast({
            title: '支付失败',
            icon: 'none'
          })
        }
      })
    }, err => {
      wx.showToast({
        title: err,
        icon: "none"
      })
    })
  },
  onclickSure(){
    if (this.data.fileListImg.length > 0) {
      this.upDataFile(this.data.fileListImg, 0, 1);
      return false;
    }
  },
  hidetoast(){
    this.setData({
      toast:false
    })
  },
  dateClose(){
    this.setData({
      detePopup:false
    })
  },
  showDate(){
    this.setData({
      detePopup:true
    })
  },
  dateRight(){
    debugger
    if(this.data.ageDate[1]>this.data.ageDate[0]){
      this.setData({
        ['factoryJob.age']:this.data.miny[this.data.ageDate[0]]+'-'+this.data.maxy[this.data.ageDate[1]]
      })
    }
    this.dateClose()
  },
  bindChange(e){
    this.setData({ageDate:e.detail.value})
  }
})